package com.bilicute.libman.controller;

import com.bilicute.libman.pojo.Result;
import com.bilicute.libman.pojo.User;
import com.bilicute.libman.quickMethods.QuickMethods;
import com.bilicute.libman.quickMethods.VerifyCodeMethods;
import com.bilicute.libman.service.UserService;
import com.bilicute.libman.util.JwtUtil;
import com.bilicute.libman.util.Sha256Util;
import com.bilicute.libman.util.StringUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static com.bilicute.libman.quickMethods.VerifyCodeMethods.verifyByMail;

/**
 * @所属包名: com.bilicute.libman.controller
 * @类名: UserController
 * @作者: i囡漫笔
 * @描述: 用户应用程序的入口点
 * @创建时间: 2024-06-20 06:54
 */

@RestController
@CrossOrigin
@RequestMapping("/api/user")
@Validated
public class UserController {

    private UserService userService;
    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    @PostMapping("/register")
    public Result<String> register(String username,
                                   String password ,
                                   String mail ,
                                   String code,
                                   HttpServletRequest request){
        if (StringUtil.noGreaterThan6(username)) return Result.error("用户名长度小于6或含有空格");
        if (StringUtil.noGreaterThan6(password)) return Result.error("密码长度小于6或含有空格");
        if (mail == null) return Result.error("邮箱为空");
        if (!StringUtil.isEmail(mail)) return Result.error("邮箱输入错误");
        if ( userService.findByUserName(username) != null ) return Result.error("用户名已存在");
        if (userService.getUserByEmail(mail)!=null) return Result.error("邮箱已被注册");
        if (!verifyByMail(request,mail,code)) return Result.error("邮箱验证码错误");

        userService.register(username,password,mail);
        request.getSession().invalidate();
        return Result.success();
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp ="^\\S{5,16}$" , message = "用户名长度不符合规则5-16\n") @NotNull(message = "用户名为空") String username,
                        @Pattern(regexp ="^\\S{5,16}$" , message = "密码长度不符合规则5-16\n") @NotNull(message = "密码为空") String password,
                        String code,
                        HttpServletResponse response,
                        HttpServletRequest request){
        if (!VerifyCodeMethods.verifyByImg(request,code)) {
            return Result.error("验证码错误");
        }
        // 根据用户名查询用户
        User loginUser=userService.findByUserName(username);
        // 判断该用户是否存在
        if(loginUser==null) return Result.error("用户名或密码错误");

        // 判断密码是否正确loginUser对象中的password是密文
        if (Sha256Util.addSalt(password).equals(loginUser.getUser_password()) ){
            // 登录成功
            // DONE 完成获取JWT的令牌返回到cookie
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getUser_id());
            claims.put("username",loginUser.getUser_name());
            String token = JwtUtil.genToken(claims);
            Cookie cookie = new Cookie("jwt", token);
            cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
            // cookie.setSecure(true);
            cookie.setHttpOnly(true);
            cookie.setPath("/");
            response.addCookie(cookie);
            request.getSession().invalidate();
            return Result.success(token);
        }
        return Result.error("用户名或密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(){
        //根据用户名查询用户
        User user = QuickMethods.getLoggedUser();
        if (user == null) return Result.error("查询信息错误");
        return Result.success(user);
    }

    @GetMapping("/getUser")
    public Result<User> getUser(Integer userId){
        //根据用户名查询用户
        User user = userService.findByUserId(userId);
        if (user == null) return Result.error("查询信息错误");
        return Result.success(user);
    }

    @GetMapping("/out")
    public Result<String> deleteAllUserCookies(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie("jwt", null);
        cookie.setMaxAge(0);
        // cookie.setSecure(true);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);
        request.getSession().invalidate();
        return Result.success();
    }

}
